<template>
  <div class="wrapper">
    <h1>登录页面</h1>
    <el-form ref="form" :model="form" label-width="80px" style="width: 400px; max-height: 300px;" :rules="rules">
      <el-form-item label="用户名称" prop="username">
        <el-input v-model="form.username" type="text"></el-input>
      </el-form-item>
      <el-form-item label="用户密码" prop="password">
        <el-input v-model="form.password" :type="showPassword ? 'text' : 'password'"></el-input><el-button @click="showPassword = !showPassword" type="text">{{showPassword ? '隐藏密码' : '显示密码'}}</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="HandleLogin" :disabled="isLoading">登录</el-button>
  </div>
</template>
<script>
import { Message } from 'element-ui';

export default {
  name: 'Login',
  data() {
    return {
      showPassword: false,
      flag: true,
      timer: null,
      isLoading: false,
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户名称密码', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
      }
    }
  },
  methods: {
     HandleLogin(){
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.isLoading) return;
          this.isLoading = true;
          try {
            await this.$store.dispatch('userAuth/getUserInfo',{ username:this.form.username, password:this.form.password })
            this.$router.push({path: '/layout'}).catch((err) => {
              console.log(err);
            });
            
          } catch (error) {
            console.log(error);
            
          } finally {
            this.isLoading = false;
          }
        } else {
          if(this.flag){
            Message.error('请输出正确的用户名和密码');
            this.flag = false;
            this.timer = setTimeout(() => {
              this.flag = true
              this.timer = null
            }, 2000)
          }
        }
      })
    }
  }
}
</script>